// src/containers/InterviewResult/index.jsx - 更新API调用
import { useState, useEffect } from 'react'
import { useParams, Link } from 'react-router-dom'
import { 
  Download, Star, TrendingUp, Clock, Eye, 
  CheckCircle, AlertCircle, BarChart3, PieChart,
  FileText, Home, RotateCcw
} from 'lucide-react'
import { api } from '../../utils/api' // 导入API工具
import './style.css'

const InterviewResult = () => {
  const { sessionId } = useParams()
  const [resultData, setResultData] = useState(null)
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState('overview')
  const [downloadLoading, setDownloadLoading] = useState(false)

  useEffect(() => {
    loadResultData()
  }, [sessionId])

  const loadResultData = () => {
    // 模拟加载结果数据
    // 在实际应用中，这里应该调用API获取结果数据
    setTimeout(() => {
      setResultData({
        overall_score: 85,
        interview_duration: 1245, // 秒
        total_rounds: 3,
        job_position: '软件工程师',
        completion_time: new Date().toLocaleString(),
        scores: {
          technical_skills: 88,
          communication: 82,
          problem_solving: 90,
          cultural_fit: 80,
          experience: 85
        },
        emotion_analysis: {
          confidence: 75,
          stress_level: 'medium',
          engagement: 88,
          authenticity: 92,
          dominant_emotions: [
            { emotion: '自信', percentage: 35, color: '#10b981' },
            { emotion: '专注', percentage: 28, color: '#3b82f6' },
            { emotion: '紧张', percentage: 20, color: '#f59e0b' },
            { emotion: '兴奋', percentage: 12, color: '#8b5cf6' },
            { emotion: '其他', percentage: 5, color: '#6b7280' }
          ]
        },
        performance_highlights: [
          '技术问题回答详细且准确',
          '表达清晰，逻辑性强',
          '展现了良好的学习能力',
          '对行业趋势有深入理解'
        ],
        improvement_areas: [
          '可以更多展示实际项目经验',
          '回答时可以更加简洁',
          '建议加强系统设计知识'
        ],
        detailed_feedback: [
          {
            round: 1,
            question: '请简单介绍一下自己的技术背景',
            score: 85,
            feedback: '回答全面，技术栈介绍清晰，但可以更多强调项目经验。',
            emotion_data: '整体表现自信，情绪稳定'
          },
          {
            round: 2,
            question: '如何优化一个查询缓慢的数据库？',
            score: 90,
            feedback: '技术方案合理，思路清晰，展现了良好的问题分析能力。',
            emotion_data: '思考时略显紧张，但回答时重获自信'
          },
          {
            round: 3,
            question: '描述一个你解决的技术难题',
            score: 82,
            feedback: '案例选择得当，但可以更详细地描述解决过程和结果。',
            emotion_data: '表达热情，对技术的兴趣明显'
          }
        ]
      })
      setLoading(false)
    }, 2000)
  }

  const downloadReport = async () => {
    try {
      setDownloadLoading(true)
      // 使用API工具下载报告
      await api.downloadEmotionReport(sessionId)
      console.log('报告下载成功')
    } catch (error) {
      console.error('下载报告失败:', error)
      alert('下载失败，请重试')
    } finally {
      setDownloadLoading(false)
    }
  }

  const getScoreColor = (score) => {
    if (score >= 90) return '#10b981'
    if (score >= 80) return '#3b82f6'
    if (score >= 70) return '#f59e0b'
    return '#ef4444'
  }

  const getScoreLevel = (score) => {
    if (score >= 90) return '优秀'
    if (score >= 80) return '良好'
    if (score >= 70) return '合格'
    return '需改进'
  }

  const formatDuration = (seconds) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}分${secs}秒`
  }

  if (loading) {
    return (
      <div className="interview-result loading">
        <div className="loading-container">
          <div className="analysis-animation">
            <div className="brain-icon">🧠</div>
            <div className="loading-bars">
              <div className="bar"></div>
              <div className="bar"></div>
              <div className="bar"></div>
              <div className="bar"></div>
            </div>
          </div>
          <h2>AI正在分析您的面试表现...</h2>
          <p>请稍候，我们正在生成详细的面试报告</p>
          <div className="analysis-steps">
            <div className="step active">语音识别分析</div>
            <div className="step active">情绪变化分析</div>
            <div className="step active">回答质量评估</div>
            <div className="step">生成综合报告</div>
          </div>
        </div>
      </div>
    )
  }

  if (!resultData) {
    return (
      <div className="interview-result error">
        <div className="error-container">
          <AlertCircle size={64} />
          <h2>无法加载面试结果</h2>
          <p>抱歉，系统暂时无法生成您的面试报告</p>
          <Link to="/home" className="retry-btn">返回首页</Link>
        </div>
      </div>
    )
  }

  return (
    <div className="interview-result">
      <div className="result-container">
        {/* 头部概览 */}
        <div className="result-header">
          <div className="score-overview">
            <div className="overall-score">
              <div className="score-circle">
                <div className="score-text">
                  <span className="score-number">{resultData.overall_score}</span>
                  <span className="score-label">分</span>
                </div>
                <svg className="score-ring" viewBox="0 0 120 120">
                  <circle 
                    cx="60" 
                    cy="60" 
                    r="50" 
                    fill="none" 
                    stroke="#e5e7eb" 
                    strokeWidth="8"
                  />
                  <circle 
                    cx="60" 
                    cy="60" 
                    r="50" 
                    fill="none" 
                    stroke={getScoreColor(resultData.overall_score)}
                    strokeWidth="8"
                    strokeLinecap="round"
                    strokeDasharray={`${resultData.overall_score * 3.14}, 314`}
                    transform="rotate(-90 60 60)"
                  />
                </svg>
              </div>
              <div className="score-info">
                <h3>综合评分</h3>
                <p className="score-level">{getScoreLevel(resultData.overall_score)}</p>
              </div>
            </div>

            <div className="interview-summary">
              <h2>面试完成！</h2>
              <div className="summary-grid">
                <div className="summary-item">
                  <Clock size={20} />
                  <span>{formatDuration(resultData.interview_duration)}</span>
                </div>
                <div className="summary-item">
                  <Eye size={20} />
                  <span>{resultData.total_rounds} 轮面试</span>
                </div>
                <div className="summary-item">
                  <CheckCircle size={20} />
                  <span>{resultData.job_position}</span>
                </div>
              </div>
              <p className="completion-time">完成时间：{resultData.completion_time}</p>
            </div>
          </div>

          <div className="action-buttons">
            <button 
              className="download-btn" 
              onClick={downloadReport}
              disabled={downloadLoading}
            >
              {downloadLoading ? (
                <div className="loading-spinner"></div>
              ) : (
                <>
                  <Download size={20} />
                  下载详细报告
                </>
              )}
            </button>
            <Link to="/prep" className="restart-btn">
              <RotateCcw size={20} />
              重新面试
            </Link>
            <Link to="/home" className="home-btn">
              <Home size={20} />
              返回首页
            </Link>
          </div>
        </div>

        {/* 标签页导航 */}
        <div className="tab-navigation">
          <button 
            className={`tab-btn ${activeTab === 'overview' ? 'active' : ''}`}
            onClick={() => setActiveTab('overview')}
          >
            <BarChart3 size={18} />
            能力评估
          </button>
          <button 
            className={`tab-btn ${activeTab === 'emotion' ? 'active' : ''}`}
            onClick={() => setActiveTab('emotion')}
          >
            <PieChart size={18} />
            情绪分析
          </button>
          <button 
            className={`tab-btn ${activeTab === 'feedback' ? 'active' : ''}`}
            onClick={() => setActiveTab('feedback')}
          >
            <FileText size={18} />
            详细反馈
          </button>
        </div>

        {/* 标签页内容 */}
        <div className="tab-content">
          {activeTab === 'overview' && (
            <div className="overview-tab">
              <div className="scores-grid">
                {Object.entries(resultData.scores).map(([skill, score]) => (
                  <div key={skill} className="score-card">
                    <div className="skill-name">
                      {skill === 'technical_skills' && '技术能力'}
                      {skill === 'communication' && '沟通表达'}
                      {skill === 'problem_solving' && '问题解决'}
                      {skill === 'cultural_fit' && '文化契合'}
                      {skill === 'experience' && '经验匹配'}
                    </div>
                    <div className="skill-score">
                      <span className="score">{score}</span>
                      <div className="score-bar">
                        <div 
                          className="score-fill"
                          style={{ 
                            width: `${score}%`,
                            background: getScoreColor(score)
                          }}
                        ></div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              <div className="highlights-section">
                <div className="highlights-card">
                  <h4>✨ 表现亮点</h4>
                  <ul>
                    {resultData.performance_highlights.map((highlight, index) => (
                      <li key={index}>{highlight}</li>
                    ))}
                  </ul>
                </div>

                <div className="improvements-card">
                  <h4>📈 改进建议</h4>
                  <ul>
                    {resultData.improvement_areas.map((area, index) => (
                      <li key={index}>{area}</li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'emotion' && (
            <div className="emotion-tab">
              <div className="emotion-overview">
                <div className="emotion-stats">
                  <div className="stat-card">
                    <h4>自信指数</h4>
                    <div className="stat-value">{resultData.emotion_analysis.confidence}%</div>
                  </div>
                  <div className="stat-card">
                    <h4>压力水平</h4>
                    <div className="stat-value">
                      {resultData.emotion_analysis.stress_level === 'low' && '较低'}
                      {resultData.emotion_analysis.stress_level === 'medium' && '中等'}
                      {resultData.emotion_analysis.stress_level === 'high' && '较高'}
                    </div>
                  </div>
                  <div className="stat-card">
                    <h4>参与度</h4>
                    <div className="stat-value">{resultData.emotion_analysis.engagement}%</div>
                  </div>
                  <div className="stat-card">
                    <h4>真实性</h4>
                    <div className="stat-value">{resultData.emotion_analysis.authenticity}%</div>
                  </div>
                </div>

                <div className="emotion-chart">
                  <h4>情绪分布图</h4>
                  <div className="emotion-bars">
                    {resultData.emotion_analysis.dominant_emotions.map((emotion, index) => (
                      <div key={index} className="emotion-bar">
                        <div className="emotion-label">{emotion.emotion}</div>
                        <div className="emotion-progress">
                          <div 
                            className="emotion-fill"
                            style={{ 
                              width: `${emotion.percentage}%`,
                              background: emotion.color
                            }}
                          ></div>
                        </div>
                        <div className="emotion-percentage">{emotion.percentage}%</div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'feedback' && (
            <div className="feedback-tab">
              {resultData.detailed_feedback.map((item, index) => (
                <div key={index} className="feedback-card">
                  <div className="feedback-header">
                    <h4>第 {item.round} 轮面试</h4>
                    <div className="feedback-score">
                      <Star size={16} fill={getScoreColor(item.score)} color={getScoreColor(item.score)} />
                      <span>{item.score}分</span>
                    </div>
                  </div>
                  
                  <div className="question-section">
                    <h5>面试问题：</h5>
                    <p>{item.question}</p>
                  </div>

                  <div className="feedback-content">
                    <div className="feedback-text">
                      <h5>表现评价：</h5>
                      <p>{item.feedback}</p>
                    </div>
                    
                    <div className="emotion-feedback">
                      <h5>情绪表现：</h5>
                      <p>{item.emotion_data}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default InterviewResult